package com.oyc.demo.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oyc.demo.domain.Cablebasic;
import com.oyc.demo.service.ClientService;
import com.oyc.demo.service.UserService;
import com.oyc.demo.util.Constants;
import com.oyc.demo.util.Result;

import io.swagger.annotations.ApiOperation;

/**
 * (Client)表控制层
 *
 * @author 杜学森
 * @since 2021-01-20 18:51:53
 */
@RestController
@RequestMapping("/client")
public class ClientController {  
    /**
     * 服务对象
     */
    @Autowired
    private ClientService clientService;
    @Autowired
    private UserService userService;
    
    SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");  

    @RequestMapping(value="/update",method= RequestMethod.POST)
    @ApiOperation("修改电缆接口")
    public Result<String> update(HttpServletRequest requetst) {
    	
    	Cablebasic client=new Cablebasic();
    	
    	if(requetst.getParameter("oper").equalsIgnoreCase("edit")){
    	
    		client.setId(requetst.getParameter("id"));
    		client.setFilterwavevelocity(requetst.getParameter("filterwavevelocity")); 
    		client.setFiltermeterlength(requetst.getParameter("filtermeterlength"));
    		client.setFilteractuallength(requetst.getParameter("filteractuallength"));
    		client.setFiltertemperature(requetst.getParameter("filtertemperature"));
    		client.setFilterdirectresistorask(requetst.getParameter("filterdirectresistorask"));
    		client.setFilterdirectresistoractual(requetst.getParameter("filterdirectresistoractual")); 
    		client.setFilteractualcrossarea(requetst.getParameter("filteractualcrossarea"));
    		client.setFiltertestdate(requetst.getParameter("filtertestdate"));
    		client.setFiltertestresult(requetst.getParameter("filtertestresult"));
    		client.setTipsamplenumber(requetst.getParameter("tipsamplenumber")); 
    		client.setTipdirectresistoractual(requetst.getParameter("tipdirectresistoractual")); 
    		client.setTiptestdate(requetst.getParameter("tiptestdate"));
    		client.setTiptestresult(requetst.getParameter("tiptestresult"));
    		client.setTiptestreportnumber(requetst.getParameter("tiptestreportnumber"));
    		client.setTiptestunitname(requetst.getParameter("tiptestunitname")); 
    		client.setIntersamplenumber(requetst.getParameter("intersamplenumber"));
    		client.setInterdirectresistoractual(requetst.getParameter("interdirectresistoractual"));
    		client.setIntertestdate(requetst.getParameter("intertestdate"));
	    	client.setIntertestresult(requetst.getParameter("intertestresult"));
	    	client.setIntertestreportnumber(requetst.getParameter("intertestreportnumber")); 
	    	client.setIntertestunitname(requetst.getParameter("intertestunitname"));
	    	client.setTestresult(requetst.getParameter("testresult"));
	    	client.setObjectionhanding(requetst.getParameter("objectionhanding"));
	    	client.setRemark(requetst.getParameter("remark"));
    	
	    	try {
	            clientService.update(client);
	            return Result.success("修改电缆信息成功");
	        }catch (Exception e){
	        	e.printStackTrace();
	            return Result.error("数据格式异常，请检查",500);
	        }
    	
    	}else{
    		return Result.success("修改电缆信息成功");
    	}
    }

    @RequestMapping(value="/selectbycondition",method= RequestMethod.POST)
    @ApiOperation("查询电缆接口")
    public JSONObject selectByCondition(HttpServletRequest requetst) {
    		Cablebasic client=new Cablebasic();
    		//配置查询参数
    		client.setProvincecompanyname(userService.findprovincename(null));
    		
    		client.setCitycompanyname(requetst.getParameter("citycompanyname"));
    		client.setSuppliername(requetst.getParameter("suppliername"));
    		
    		if(requetst.getParameter("goodsname")!=null&&!requetst.getParameter("goodsname").equals("全部")) {
        		client.setGoodsname(requetst.getParameter("goodsname"));
        	}
    		if(requetst.getParameter("filtertestresult")!=null&&!requetst.getParameter("filtertestresult").equals("全部")) {
            	//预筛选结果不准确
                if(requetst.getParameter("filtertestresult").equals("不准确")) {
                	client.setRemark("预筛选结果不准确");
        		}else{
        			client.setFiltertestresult(requetst.getParameter("filtertestresult"));
        		}
    		}
    		if(requetst.getParameter("tiptestresult")!=null&&!requetst.getParameter("tiptestresult").equals("全部")) {
    			client.setTiptestresult(requetst.getParameter("tiptestresult"));
    		}
    		if(requetst.getParameter("intertestresult")!=null&&!requetst.getParameter("intertestresult").equals("全部")) {
    			client.setIntertestresult(requetst.getParameter("intertestresult"));
    		}
    		
            
            PageHelper.startPage(Integer.parseInt(requetst.getParameter("page")), Integer.parseInt(requetst.getParameter("rows")));
            //查询数据
            List<Map<String, String>> listClient = clientService.queryAll(client);
        
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(listClient);

        JSONObject oJson = new JSONObject();
        oJson.put("records", pageInfo.getTotal());
        oJson.put("total", pageInfo.getPages());
        oJson.put("page", pageInfo.getPageNum());
        
        List<Map<String, String>> list=pageInfo.getList();
        
        if(list!=null&&list.size()>0){
            JSONArray array=new JSONArray();
            for (int i = 0; i < list.size(); i++) {
            	Map<String, String> map=list.get(i);
                JSONObject obj=new JSONObject();
                obj.put("id", map.get("id"));
                
                JSONArray innerarray=new JSONArray();
                innerarray.add(map.get("ordernumber"));
                innerarray.add(map.get("reelnumber"));
                innerarray.add(map.get("provincecompanyname"));
                innerarray.add(map.get("citycompanyname"));
                innerarray.add(map.get("warehousename"));
                innerarray.add(map.get("suppliername"));
                innerarray.add(map.get("suppliercode"));
                innerarray.add(map.get("goodsname"));
                innerarray.add(map.get("goodsdescribe"));
                innerarray.add(map.get("goodscode"));
                innerarray.add(map.get("enterdate"));
                innerarray.add(map.get("filterwavevelocity"));
                innerarray.add(map.get("filtermeterlength"));
                innerarray.add(map.get("filtertemperature"));
                innerarray.add(map.get("filteractuallength"));
                innerarray.add(map.get("filterdirectresistorask"));
                innerarray.add(map.get("filterdirectresistoractual"));
                innerarray.add(map.get("filteractualcrossarea"));
                innerarray.add(map.get("filtertestdate"));
                innerarray.add(map.get("filtertestresult"));
                innerarray.add(map.get("tipsamplenumber"));
                innerarray.add(map.get("tipdirectresistoractual"));
                innerarray.add(map.get("tiptestdate"));
                innerarray.add(map.get("tiptestresult"));
                innerarray.add(map.get("tiptestreportnumber"));
                innerarray.add(map.get("tiptestunitname"));
                innerarray.add(map.get("intersamplenumber"));
                innerarray.add(map.get("interdirectresistoractual"));
                innerarray.add(map.get("intertestdate"));
                innerarray.add(map.get("intertestresult"));
                innerarray.add(map.get("intertestreportnumber"));
                innerarray.add(map.get("intertestunitname"));
                innerarray.add(map.get("testresult"));
                innerarray.add(map.get("objectionhanding"));
                innerarray.add(map.get("remark"));
                obj.put("cell", innerarray);
                array.add(obj);
            }
            oJson.put("rows", array);
        }
        return oJson;
    }
   
    @RequestMapping(value="/exportexcel",method= RequestMethod.GET)
    @ApiOperation("导出")
    public void exportexcel(HttpServletRequest requetst,HttpServletResponse response) {
    	
    	ServletOutputStream outputStream=null;
    	
        try {
        	
        	Cablebasic client=new Cablebasic();
       	 	//配置查询参数
        	client.setProvincecompanyname(userService.findprovincename(null));
        	//查询数据
        	List<Cablebasic> listClient = clientService.queryExcel(client);
        	
            // 这里 会填充到第一个sheet， 然后文件流会自动关闭
            
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("成盘线缆检测结果清单"+sdf.format(new Date()),"UTF-8") + ".xlsx");
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            
            outputStream = response.getOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(Constants.templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(listClient, fillConfig, writeSheet);
            excelWriter.finish();
        }catch (Exception e){
        	e.printStackTrace();
        }finally {
            if(outputStream!=null){
            	try {
					outputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }

    }

}